package com.codedef.diary;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.appcompat.app.ActionBar;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.codedef.diary.config.Config;
import com.codedef.diary.config.HandlerInfo;
import com.codedef.diary.config.SharedConfig;
import com.codedef.diary.config.UrlConfig;
import com.codedef.diary.domain.Diary;
import com.codedef.diary.domain.MyImageView;
import com.codedef.diary.util.DateUtil;
import com.codedef.diary.util.NetWorkUtil;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.edittext.MultiLineEditText;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.StringJoiner;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.xuexiang.xui.XUI.getContext;

public class NewDiaryActivity extends AppCompatActivity {

    // 需要的权限
    private final static String[] permissions = {
            "android.permission.ACCESS_FINE_LOCATION",
            "android.permission.ACCESS_COARSE_LOCATION",
            "android.permission.WRITE_EXTERNAL_STORAGE"
    };

    private static final int SET_WEATHER = 10001, SET_CITY = 10002, SET_IMG_URL = 20001;
    private static final int CHOOSE_PHOTO = 2;

    Toolbar toolbar;
    TextView tvLocation, tvWeather;
    MultiLineEditText edContent;
    MyImageView[] imageViews;
//    String[] imagesPath;

    private int counter = 0, imageIndex = 0;

    Diary diary;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HandlerInfo.MAKE_TOAST:
                    Toast.makeText(NewDiaryActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case SET_WEATHER:
                    diary.setWeather((String) msg.obj);
                    tvWeather.setText((String) msg.obj);
                    break;
                case SET_CITY:
                    diary.setLocation((String) msg.obj);
                    tvLocation.setText((String) msg.obj);
                    break;
                case SET_IMG_URL:
                    String[] ls = diary.getPictureList();
                    ls[msg.arg1] = UrlConfig.UPLOAD_PREFIX + (String) msg.obj;
                    diary.setPictureList(ls);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_diary);
        initUi();
        if("OLD".equals(getIntent().getStringExtra("FLAG"))) {
            intiDataFromPreActivity();
        } else {
            intiData();

        }




    }

    public void initUi() {
        toolbar = findViewById(R.id.newtoolbar);
        setSupportActionBar(toolbar);

        tvLocation = findViewById(R.id.tv_location);
        tvWeather = findViewById(R.id.tv_weather);
        edContent = findViewById(R.id.ed_content);

        imageViews = new MyImageView[3];
        imageViews[0] = findViewById(R.id.img_view_1);
        imageViews[1] = findViewById(R.id.img_view_2);
        imageViews[2] = findViewById(R.id.img_view_3);

    }

    public void intiData() {
        diary = new Diary();
        // 设置Datetime
        diary.setDateTime(new Date());
        toolbar.setTitle("    " + DateUtil.outFormat(diary.getDateTime()).substring(5, 16)); //--------------------------------------------------
        diary.setPictureList(new String[3]);

        // 验证权限
        if (checkPermission(permissions[0]) && checkPermission(permissions[1])) {
            // 权限完整，获取位置与天气
            showLocationAndWeather();
        } else {
            // 缺少权限
            ActivityCompat.requestPermissions(this, permissions, 1);
        }

    }

    public void intiDataFromPreActivity() {
        // 拿到对象
        diary = (Diary) getIntent().getSerializableExtra("DIARY");
        // 设置Datetime
        toolbar.setTitle("    " + DateUtil.outFormatNYR(diary.getDateTime()).substring(0, 17));
        // 位置
        tvLocation.setText(diary.getLocation());
        // 天气
        tvWeather.setText(diary.getWeather());
        // 内容
        edContent.setContentText(diary.getContent());
        // 图片
        for(int i=0; i<diary.getPictureList().length; i++)
            imageViews[i].setImageURL(diary.getPictureList()[i]);

    }

    public void onAddImageButtonClick(View view) {
        // 验证权限
        if (checkPermission(permissions[2])) {
            // 权限完整，选择图片
            switch (view.getId()) {
                case R.id.img_view_1:
                    imageIndex = 0;
                    break;
                case R.id.img_view_2:
                    imageIndex = 1;
                    break;
                case R.id.img_view_3:
                    imageIndex = 2;
                    break;
            }
            openAlbum();
        } else {
            // 缺少权限
            ActivityCompat.requestPermissions(this, permissions, 2);
        }
    }

    private void onSubmitButtonClick() {
        if(edContent.getContentText() == null || "".equals(edContent.getContentText())) {
            // 内容为空，弹出Toast提示
            Toast.makeText(NewDiaryActivity.this, "输入点内容吧~", Toast.LENGTH_SHORT).show();
            return;
        }
        diary.setContent(edContent.getContentText());
        postDiary(diary);


    }

    private void delDiary() {
        SharedPreferences sp = getSharedPreferences(SharedConfig.SHARED_MODEL_NAME, Context.MODE_PRIVATE);
        final String session = sp.getString(SharedConfig.KEY_SESSION, null);

        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = NetWorkUtil.get(UrlConfig.DEL_DIARY + diary.getId(), session);
                if(result != null) {
                    Message message = new Message();
                    message.what = HandlerInfo.MAKE_TOAST;
                    message.obj = "删除成功";
                    handler.sendMessage(message);
                }
            }
        }).start();
    }

    private void postDiary(final Diary diary) {
        SharedPreferences sp = getSharedPreferences(SharedConfig.SHARED_MODEL_NAME, Context.MODE_PRIVATE);
        final String session = sp.getString(SharedConfig.KEY_SESSION, null);

        new Thread(new Runnable() {
            @Override
            public void run() {
                StringJoiner joiner = new StringJoiner("~");
                for (String string : diary.getPictureList()) {
                    joiner.add(string);
                }
                OkHttpClient client = new OkHttpClient();
                FormBody.Builder builder = new FormBody.Builder()
                        .add("content", diary.getContent())
                        .add("weather", diary.getWeather())
                        .add("location", diary.getLocation())
                        .add("dateTime", DateUtil.outFormat(diary.getDateTime()))
                        .add("pictureList", joiner.toString());
                if(diary.getId() != null) builder.add("id", String.valueOf(diary.getId()));
                RequestBody requestBody = builder.build();
                Request request = new Request.Builder()
                        .url(UrlConfig.ADD_DIARY)
                        .header("Cookie", session)
                        .post(requestBody)
                        .build();
                Response response = null;
                String result = null;
                try {
                    response = client.newCall(request).execute();
                    result = response.body().string();
                    if("SUCCESS".equals(result)) {
                        Message message = new Message();
                        message.what = HandlerInfo.MAKE_TOAST;
                        message.obj = "提交成功";
                        handler.sendMessage(message);
                    } else {
                        Log.e("shy", "请求失败了 呜呜呜"+ result + response.code());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
        return;
    }

    private void uploadImage(final String imgPath, final int index) {
        SharedPreferences sp = getSharedPreferences(SharedConfig.SHARED_MODEL_NAME, Context.MODE_PRIVATE);
        final String session = sp.getString(SharedConfig.KEY_SESSION, null);

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 创建 OkHttpClient
                OkHttpClient client = new OkHttpClient.Builder().build();
                // 要上传的文件
                File file = new File(imgPath);
                MediaType mediaType = MediaType.parse("image/jpeg");
                // 把文件封装进请求体
                RequestBody fileBody = RequestBody.create(mediaType, file);
                // MultipartBody 上传文件专用的请求体
                RequestBody body = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM) // 表单类型(必填)
                        .addFormDataPart("file", file.getName(), fileBody)
                        .build();
                Request request = new Request.Builder()
                        .url(UrlConfig.UPLOAD)  //---------------------------------------------
                        .header("Cookie", session)  //--------------------------------------------
                        .post(body)
                        .build();
                Response response = null;
                String result = null;
                try {
                    response = client
                            .newCall(request)
                            .execute();
                    result = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.e("shy", result);
                Message message = new Message();
                message.what = SET_IMG_URL;
                message.arg1 = index;
                message.obj = result;
                handler.sendMessage(message);
            }
        }).start();

        return;
    }


    /********************* 获取位置天气部分 *********************/
    // 获取地理位置并设置天气
    private void showLocationAndWeather() {
        // 获取位置管理者对象
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        // 验证权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                        this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

        // 位置更新监听
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // 只进行一次位置获取
                if (counter++ >= 1) return;
                // 获取经纬度主要方法
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();

                Geocoder geocoder = new Geocoder(NewDiaryActivity.this);
                Address address = null;
                try {
                    // 基于经纬度进行位置的反编码
                    address = geocoder.getFromLocation(latitude, longitude, 1).get(0);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.e("shy", address.toString());
                // 获得到城市名、所在区域
//                String city = address.getSubAdminArea();
                String city = address.getLocality();
                String feature = address.getFeatureName();
                // 发送信息
                Message msg = new Message();
                msg.what = 10002;
                msg.obj = feature;
                handler.sendMessage(msg);
                // 得到城市名后，通过API接口获取天气
                showWeather(city);

            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {
                //状态发生改变监听
            }

            @Override
            public void onProviderEnabled(String s) {
                // ProviderEnabled
            }

            @Override
            public void onProviderDisabled(String s) {
                // ProviderDisabled
            }
        });

    }

    // 通过城市名获取天气
    private void showWeather(final String city) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.e("shy", "La:" + city);
                String url = "https://way.jd.com/he/freeweather?city=" + city + "&appkey=" + Config.JD_WX_APPKEY;
                String result = NetWorkUtil.get(url);
                JSONObject heWeather5obj = JSON.parseObject(result).getJSONObject("result").getJSONArray("HeWeather5").getJSONObject(0);
                Log.e("shy", heWeather5obj.toString());
                JSONObject nowObj = heWeather5obj.getJSONObject("now");
                String weather = (String) nowObj.getJSONObject("cond").get("txt");
                Message msg = new Message();
                msg.what = 10001;
                msg.obj = weather;
                handler.sendMessage(msg);
            }
        }).start();

    }


    /********************* 选择图片部分 *********************/
    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, NewDiaryActivity.CHOOSE_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CHOOSE_PHOTO:
                if(resultCode == RESULT_OK) {
                    if(Build.VERSION.SDK_INT >= 19) {
                        handleImageOnKitKat(data);
                    }

                }
                break;
        }
    }

    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if(DocumentsContract.isDocumentUri(this, uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);

            } else if("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.parseLong(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if("content".equalsIgnoreCase(uri.getScheme())) {
            imagePath = getImagePath(uri, null);
        } else if("file".equalsIgnoreCase(uri.getScheme())) {
            imagePath = uri.getPath();
        }
        displayImage(imagePath);

    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if(cursor != null) {
            if(cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    // 上传完成显示图片
    private void displayImage(String imgPath) {
        Toast.makeText(this, imgPath, Toast.LENGTH_SHORT).show();  //0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-
        Log.i("shy", Arrays.toString(diary.getPictureList()));
        uploadImage(imgPath, imageIndex);
//
//        String[] ls = diary.getPictureList();
//        ls[imageIndex] = imgPath;
//        diary.setPictureList(ls);

        if(imgPath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
            imageViews[imageIndex].setImageBitmap(bitmap); //----------------------------------------------------------------------------
        } else {
            Toast.makeText(this, "Faild", Toast.LENGTH_SHORT).show();
        }
    }


    /********************* 其他杂项部分 *********************/
    // 验证当前是否获得某一权限
    private boolean checkPermission(String s) {
        if(ContextCompat.checkSelfPermission(this, s) != PackageManager.PERMISSION_GRANTED) {
            // 缺少该权限
            return false;
        } else {
            // 该权限已有
            return true;
        }
    }

    // 授权回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 授权成功，再次执行操作
                    showLocationAndWeather();
                } else {
                    // 用户取消了授权
                    Toast.makeText(NewDiaryActivity.this, "您取消了授权", Toast.LENGTH_SHORT).show();
                }
                break;
            case 2:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 授权成功，再次执行操作

                } else {
                    // 用户取消了授权
                    Toast.makeText(NewDiaryActivity.this, "您取消了授权", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    public  boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.new_toolbar,menu);
        return true;
    }

    //toolbar菜单选择
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.d_btn:
                onSubmitButtonClick();
                break;
            case R.id.del:
                AlertDialog.Builder builder = new AlertDialog.Builder(this).setIcon(R.drawable.icon_warning).setTitle("警告")
                        .setMessage("确认要删除这篇日记吗").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                delDiary();
                                finish();
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
//                                dialogInterface.dismiss();
                            }
                        });
                builder.create().show();



                break;
            case R.id.choose:
                Toast.makeText(this,"You clicked  choose",Toast.LENGTH_SHORT).show();
                break;
            default:
        }
        return true;
    }

}